<template>
  <div id="DailySurvey-map" style="width:100%;height:658px;"></div>
</template>
<script>
import '@/assets/map/ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import VectorLayer from 'ol/layer/Vector';
import {Vector as VectorSource} from 'ol/source';
import { getProjection,getResolutions,getTiandituVecMap,getTiandituVecText,getTiandituImgMap,getTiandituImgText,
  getRESTLayer,getVectorTileLayer,iServerHttp,meterToDegree,degreeToMeter } from "@/map/projMap.js";
import {boundingExtent} from 'ol/extent';
import WKT from 'ol/format/WKT';
import LineString from 'ol/geom/LineString';
import Point from 'ol/geom/Point';
import Feature from 'ol/Feature';
import {Fill, Stroke, Style, Icon, Circle as CircleStyle,Text} from 'ol/style';
import dingweiImg from '@/assets/map/image/newImage/blueMarker.png';
import redImg from '@/assets/map/image/fwType/5.png';

export default {
  name: "DailySurvey",
  components: {

  },
  props: {
    allGeomList: {//任务空间数据列表
      type:Array,
      required:false,
      default: []
    },
    allGeomListCar: {//抽样点数据列表
      type:Array,
      required:false,
      default: []
    },
    trajectoryLine: {
      type:Array,
      required:false,
      default: []
    },
    typeLayer: {
      type: String,
      required: true,
      default: ''
    },
    clearFeature: {
      type: Boolean,
      required: true,
      default: false
    },
    clearFeatureCar: {
      type: Boolean,
      required: true,
      default: false
    }
  },
  data() {
    return {
      str: "DailySurvey",
      map: null,
      center: [105, 34],
      zoom: 4,
      layer1:null,//天地图街道图
      layer2:null,
      taskDataLayer: null,
      sampleDataLayer: null,
      taskDataArray: [],
      sampleDataArray: [],
      featureType: '',
    }
  },
  watch: {
    allGeomList: {//任务空间数据列表
      handler: function(newVal,oldVal){
        console.log("任务空间数据列表");
        console.log(newVal);
        this.taskDataArray = newVal;
        this.showTaskDataArray();//显示任务空间数据列表
      },
      immediate:true
    },
    allGeomListCar: {//抽样点数据列表
      handler: function(newVal,oldVal){
        console.log("任务空间数据列表");
        console.log(newVal);
        this.taskDataArray = newVal;
        this.showSampleDataArray();//显示抽样点数据列表
      },
      immediate:true
    },
    trajectoryLine: {//抽样点数据列表
      handler: function(newVal,oldVal){
          this.createTrajectoryLine(newVal)//移除所选择的点
      },
      immediate:true
    },
    typeLayer: {
      handler: function (newVal,oldVal) {
        this.featureType = newVal
      },
      immediate: true
    },
    clearFeature: {
      handler: function (newVal,oldVal) {
        if(newVal) {
          this.clearSource()
        }
      },
      immediate: true
    },
    clearFeatureCar: {
      handler: function (newVal,oldVal) {
        if(newVal) {
          this.clearSource()
        }
      },
      immediate: true
    }
  },
  mounted() {
    console.log("mounted");
    let that = this;
    //地图异步加载
    this.$nextTick(function(){
      console.log('地图异步加载');
      //地图异步加载
      setTimeout(() => {
        //初始化地图信息
        that.initMap();
      }, 200);
    });
  },
  methods: {
    initMap() {
      let that = this;
      let mapStr = this.str;
      let targetMap = document.getElementById(mapStr+"-map");
      if(targetMap.innerHTML!=""){
        console.log("清空targetMap");
      }
      targetMap.innerHTML = "";//清空
      //自动获取地图div高度
      this.autodivheight();
      //浏览器窗口发生变化时同时变化DIV高度
      window.onresize=this.autodivheight;
      if(this.map){//避免重复加载地图
        console.log("避免重复加载地图");
        return;
      }
      console.log("初始化地图");
      //获取投影4490坐标系
      this.projection4490 = getProjection();
      //初始化地图信息
      this.map = new Map({
        target: targetMap.id,
        /*controls: defaultControls({attributionOptions: {collapsed: false}})
            .extend([new Logo()]),*/
        view: new View({
          center: this.center,
          maxZoom: 18,
          minZoom: 4,
          zoom: this.zoom,
          constrainResolution:true,//缩放地图可移动到最近的缩放级别（整数zoom级别）
          projection: 'EPSG:4490',
          // resolutions:getResolutions()
        })
      });
      //添加天地图图层
      this.layer1 = getTiandituVecMap();//fxpc天地图街道影像底图
      this.map.addLayer(this.layer1);
      this.layer2 = getTiandituVecText();//fxpc天地图街道地图注记
      this.map.addLayer(this.layer2);
      this.layer1.setZIndex(0);
      this.layer2.setZIndex(0);
      //任务空间数据图层
      this.taskDataLayer = new VectorLayer({
        source: new VectorSource({
          wrapX: false
        }),
        projection: 'EPSG:4490'
      });
      this.map.addLayer(this.taskDataLayer);
      this.taskDataLayer.setZIndex(1);
      //抽样点数据图层
      this.sampleDataLayer = new VectorLayer({
        source: new VectorSource({
          wrapX: false
        }),
        projection: 'EPSG:4490'
      });
      this.map.addLayer(this.sampleDataLayer);
      this.sampleDataLayer.setZIndex(2);
    },
    createTrajectoryLine(list) {
      this.taskDataLayer.getSource().clear();
      if(list.length != 0) {
        let lineStringList = []
        for(let i = 0;i < list.length;i++) {
          let wkt = new WKT().readFeature(list[i].geom)
          let coordinate = wkt.getGeometry().getCoordinates()
          lineStringList.push(coordinate)
        }
        let feature = new Feature({
          geometry: new LineString(lineStringList)
        })
        let style = this.getLineStringStyle('red')
        // let style = this.getPointImgStyle()
        feature.setProperties({
          type: this.featureType,//类型
        });
        feature.setStyle(style);
        this.taskDataLayer.getSource().addFeature(feature);
      }
    },
    clearSource() {
      debugger
      let layersListTask = this.taskDataLayer.getSource().getFeatures()
      if(layersListTask.length != 0) {
        for(let i = 0;i < layersListTask.length;i++) {
          let properties = layersListTask[i].getProperties()
          if(properties.type == this.featureType) {
            this.taskDataLayer.getSource().removeFeature(layersListTask[i])
          }
        }
      }
    },
    showTaskDataArray(){//显示任务空间数据列表
      if(this.taskDataLayer!=null){
        let list = this.taskDataArray;
        if(list!=null && list.length>0){
          //全部经纬度
          let allCoordinates = [];
          for(let i=0;i<list.length;i++){
            let style = this.getPointImgStyle();
            let geomText = list[i].geom;//空间数据
            if(geomText!=null && geomText!="" && geomText!="POLYGON EMPTY"){
              //空间数据
              let featureTmp = new WKT().readFeature(geomText);
              //设置属性
              featureTmp.setProperties({
                type: this.featureType,//类型
              });
              featureTmp.setStyle(style);
              //添加矢量数据
              this.taskDataLayer.getSource().addFeature(featureTmp);
              //获取范围
              let extent = featureTmp.getGeometry().getExtent();
              if(extent.length==4){
                //全部经纬度--左下角
                allCoordinates.push([extent[0],extent[1]]);
                //全部经纬度--右上角
                allCoordinates.push([extent[2],extent[3]]);
              }
            }
          }
          this.showBoundingExtent(allCoordinates);//缩放到区域位置
        }
      }
    },
    showSampleDataArray(){//显示抽样点数据列表
      if(this.taskDataLayer!=null){
        let list = this.taskDataArray;
        if(list!=null && list.length>0){
          //全部经纬度
          let allCoordinates = [];
          for(let i=0;i<list.length;i++){
            let style = this.getPointImgStyleCar();
            let geomText = list[i].geom;//空间数据
            if(geomText!=null && geomText!="" && geomText!="POLYGON EMPTY"){
              //空间数据
              let featureTmp = new WKT().readFeature(geomText);
              //设置属性
              featureTmp.setProperties({
                type: this.featureType,//类型
              });
              featureTmp.setStyle(style);
              //添加矢量数据
              this.taskDataLayer.getSource().addFeature(featureTmp);
              //获取范围
              let extent = featureTmp.getGeometry().getExtent();
              if(extent.length==4){
                //全部经纬度--左下角
                allCoordinates.push([extent[0],extent[1]]);
                //全部经纬度--右上角
                allCoordinates.push([extent[2],extent[3]]);
              }
            }
          }
          this.showBoundingExtent(allCoordinates);//缩放到区域位置
        }
      }
    },
    getPolyonStyle(color){//多边形样式
      let style = new Style({
        fill:new Fill({//填充样式
          color:"rgba(0,0,0,0)"
        }),
        stroke:new Stroke({//描绘
          width:2,//宽
          color:color
        })
      });

      return style;
    },
    getPointImgStyleCar() {
      let style = new Style({
          image: new Icon({
            src: redImg,
            // anchor: [0.5, 1]
            anchor: [0.5, 0.8]
          }),
        });
      return style;
    },
    getPointImgStyle(){// 点图标样式
      let style = new Style({
          image: new Icon({
            src: dingweiImg,
            // anchor: [0.5, 1]
            anchor: [0.5, 0.8]
          }),
        });
      return style;
    },
    showBoundingExtent(coordinates){//缩放到区域位置
      console.log("缩放到区域位置");
      if (coordinates!=null && coordinates.length > 1) {
        const extent = boundingExtent(coordinates);
        //this.map.getView().fit(extent, {duration: 1000, padding: [50, 50, 50, 50]});
        this.map.getView().fit(extent, {padding: [50, 50, 50, 50]});
        //获取默认位置
        this.center = this.map.getView().getCenter();
        this.zoom = this.map.getView().getZoom();
      }
    },
    getLineStringStyle(color){//线样式
      let style = new Style({
        fill:new Fill({//填充样式
          color:"rgba(0,0,0,0)"
        }),
        stroke:new Stroke({//线
          width:5,//宽
          color:color
        })
      });

      return style;
    },
    autodivheight() {//自动获取div高度
      //获取浏览器窗口高度
      let winHeight = 0;
      if (window.innerHeight) {
        winHeight = window.innerHeight;
      } else if ((document.body) && (document.body.clientHeight)) {
        winHeight = document.body.clientHeight;
      }
      //通过深入Document内部对body进行检测，获取浏览器窗口高度
      if (document.documentElement && document.documentElement.clientHeight) {
        winHeight = document.documentElement.clientHeight;
      }
      //全屏时窗口高度:864px,地图div高度:754px
      let tempHeight = 864;
      let mapTempHeight = 754;
      let mapHeight = winHeight - tempHeight + mapTempHeight;
      //最小高度
      if(mapHeight<480){
        mapHeight = 480;
      }
      //设置地图高度
      document.getElementById(this.str+"-map").style.height= mapHeight +"px";
      console.log("窗口高度："+winHeight+"地图高度："+mapHeight);
      //resize事件--刷新地图,确保地图不变形
      if(this.map){
        this.map.updateSize();
        console.log("resize事件--刷新地图,确保地图不变形");
      }
    },
  }
}
</script>